<template>
  <div class="api-review">
    <!-- 动态背景 -->
    <div class="animated-bg">
      <div class="light-beam"></div>
      <div class="particles"></div>
      <div class="cyber-grid"></div>
    </div>

    <!-- 头部统计 -->
    <div class="stats-header">
      <div class="stat-card">
        <i class="fas fa-code"></i>
        <div class="stat-info">
          <div class="stat-value">{{ totalApis }}</div>
          <div class="stat-label">待审核接口</div>
        </div>
      </div>
      <div class="stat-card">
        <i class="fas fa-check-circle"></i>
        <div class="stat-info">
          <div class="stat-value">{{ approvedApis }}</div>
          <div class="stat-label">已通过</div>
        </div>
      </div>
      <div class="stat-card">
        <i class="fas fa-times-circle"></i>
        <div class="stat-info">
          <div class="stat-value">{{ rejectedApis }}</div>
          <div class="stat-label">已驳回</div>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-section glass-effect">
      <div class="filter-grid">
        <div class="filter-item">
          <label>接口名称</label>
          <el-input 
            v-model="searchParams.apiName"
            placeholder="搜索接口名称"
            prefix-icon="fas fa-search"
            clearable
          />
        </div>
        
        <div class="filter-item">
          <label>接口ID</label>
          <el-input 
            v-model="searchParams.apiId"
            placeholder="搜索接口ID"
            prefix-icon="fas fa-hashtag"
            clearable
          />
        </div>
        
        <div class="filter-item">
          <label>创建者</label>
          <el-input 
            v-model="searchParams.creator"
            placeholder="搜索创建者"
            prefix-icon="fas fa-user"
            clearable
          />
        </div>
        
        <div class="filter-item">
          <label>状态</label>
          <el-select v-model="searchParams.status" placeholder="选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <i :class="item.icon"></i>
              {{ item.label }}
            </el-option>
          </el-select>
        </div>
        
        <div class="filter-item date-range">
          <label>时间范围</label>
          <el-date-picker
            v-model="searchParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </div>
      </div>

      <div class="filter-actions">
        <el-button type="primary" @click="handleSearch">
          <i class="fas fa-search"></i>
          检索
        </el-button>
        <el-button @click="resetSearch">
          <i class="fas fa-redo"></i>
          重置
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section glass-effect">
      <el-table 
        :data="apiList"
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="name" label="接口名称">
          <template slot-scope="scope">
            <div class="api-name-cell">
              <div class="api-icon">
                <i class="fas fa-plug"></i>
              </div>
              <div class="api-info">
                <span class="api-title">{{ scope.row.name }}</span>
                <span class="api-id">#{{ scope.row.apiid }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <div :class="['status-badge', getStatusClass(scope.row.status)]">
              <i :class="getStatusIcon(scope.row.status)"></i>
              {{ getStatusText(scope.row.status) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述">
          <template slot-scope="scope">
            <div class="description-cell">
              <el-tooltip 
                :content="scope.row.description" 
                placement="top"
                :disabled="scope.row.description.length <= 50"
              >
                <span>{{ truncateText(scope.row.description, 50) }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="类型" width="120">
          <template slot-scope="scope">
            <div class="type-badge">
              <i class="fas fa-tag"></i>
              {{ scope.row.type }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建者">
          <template slot-scope="scope">
            <div class="creator-cell">
              <el-avatar 
                :src="scope.row.authorAvator" 
                :size="32"
              ></el-avatar>
              <span class="creator-name">{{ scope.row.authorName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button 
                type="success" 
                size="mini" 
                @click="handleApprove(scope.row)"
                :loading="scope.row.approving"
                v-if="scope.row.status === -2"
              >
                <i class="fas fa-check"></i>
                通过
              </el-button>
              <el-button 
                type="danger" 
                size="mini" 
                @click="handleReject(scope.row)"
                :loading="scope.row.rejecting"
                v-if="scope.row.status === -2"
              >
                <i class="fas fa-times"></i>
                驳回
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-section">
        <el-pagination
          :current-page="searchParams.currentPage"
          :page-size="searchParams.pageSize"
          :total="filteredApiList.length"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审核对话框 -->
    <el-dialog
      :title="dialogType === 'approve' ? '通过审核' : '驳回原因'"
      :visible.sync="showDialog"
      width="500px"
      custom-class="review-dialog"
    >
      <div class="dialog-content">
        <el-input
          v-if="dialogType === 'reject'"
          type="textarea"
          v-model="rejectReason"
          :rows="4"
          placeholder="请输入驳回原因"
        />
        <div v-else class="approve-confirm">
          <i class="fas fa-check-circle"></i>
          <p>确认通过该接口的审核吗？</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button 
          :type="dialogType === 'approve' ? 'success' : 'danger'"
          @click="confirmReview"
        >
          确认
        </el-button>
      </span>
    </el-dialog>

    <!-- 全局提示 -->
    <div class="toast" :class="{ 'show': showToast }">
      {{ toastMessage }}
    </div>

    <!-- 驳回原因对话框 -->
    <el-dialog
      title="驳回原因"
      :visible.sync="dialogVisible"
      width="500px"
      @closed="handleDialogClose"
    >
      <el-form :model="{ reason: rejectReason }" :rules="rejectRules" ref="rejectForm">
        <el-form-item label="驳回原因" prop="reason">
          <el-input
            type="textarea"
            v-model="rejectReason"
            :rows="4"
            placeholder="请输入驳回原因（5-200字）"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitReject">确认驳回</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ApiReview',
  data() {
    return {
      // 统计数据
      totalApis: 0,
      approvedApis: 0,
      rejectedApis: 0,

      // 筛选条件
      searchParams: {
        apiName: '',
        apiId: '',
        creator: '',
        status: '',
        dateRange: null,
        currentPage: 1,
        pageSize: 10
      },

      // 状态选项
      statusOptions: [
        { value: '5', label: '已通过', icon: 'fas fa-check text-success' },
        { value: '-2', label: '待审核', icon: 'fas fa-clock text-warning' },
        { value: '-3', label: '已驳回', icon: 'fas fa-times text-danger' }
      ],

      // 日期选择器配置
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },

      // 对话框相关
      showDialog: false,
      dialogType: 'approve',
      rejectReason: '',
      currentApi: null,

      // 提示相关
      showToast: false,
      toastMessage: '',
      toastTimer: null,

      // 添加缺失的数据属性
      apiList: [], // 添加 apiList 数组
      totalSize: 0, // 添加总数据量

      dialogVisible: false,
      rejectRules: {
        reason: [
          { required: true, message: '请输入驳回原因', trigger: 'blur' },
          { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
        ]
      }
    };
  },

  computed: {
    // 过滤后的数据
    filteredApiList() {
      if (!this.apiList) return []; // 添加空值检查
      
      return this.apiList.filter(api => {
        return (
          (!this.searchParams.apiName || api.name.includes(this.searchParams.apiName)) &&
          (!this.searchParams.apiId || api.apiid.includes(this.searchParams.apiId)) &&
          (!this.searchParams.creator || api.authorName.includes(this.searchParams.creator)) &&
          (!this.searchParams.status || api.status === this.searchParams.status)
        );
      });
    },

    // 分页后的数据
    paginatedApiList() {
      const start = (this.searchParams.currentPage - 1) * this.searchParams.pageSize;
      return this.filteredApiList.slice(start, start + this.searchParams.pageSize);
    }
  },

  methods: {

    //获取基础统计数据
    async fetchBaseStats() {
      try {
        const response = await axios.get('/api/system/api/getApiCounts');
        if (response.data.code === 200) {
          this.totalApis = response.data.data.pendingCount;
          this.approvedApis = response.data.data.passedCount;
          this.rejectedApis = response.data.data.rejectedCount;
        } else {
          this.showToastMessage(response.data.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取基础统计数据失败:', error);
        this.showToastMessage('获取数据失败');
      }
    },

    // 获取API列表
    async fetchApiList() {
      try {
        const response = await axios.post('/api/system/api/getList', {
          apiName: this.searchParams.apiName,
          apiId: this.searchParams.apiId,
          creator: this.searchParams.creator,
          status: this.searchParams.status,
          startTime: this.searchParams.dateRange?.[0],
          endTime: this.searchParams.dateRange?.[1],
          currentPage: this.searchParams.currentPage,
          pageSize: this.searchParams.pageSize
        });

        if (response.data.code === 200) {
          this.apiList = response.data.data;
          this.totalSize = response.data.total;
          this.updateStats();
        } else {
          this.showToastMessage(response.data.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取API列表失败:', error);
        this.showToastMessage('获取数据失败');
      }
      this.fetchBaseStats();
    },

    // 审核通过
    async handleApprove(api) {
      try {
        const response = await axios.post('/api/system/api/approve', {
          apiId: api.apiid
        });

        if (response.data.code === 200) {
          this.showToastMessage('审核通过成功');
          this.fetchApiList(); // 刷新列表
        } else {
          throw new Error(response.data.message || '操作失败');
        }
      } catch (error) {
        console.error('审核失败:', error);
        this.showToastMessage(error.message || '审核失败');
      }
    },

    // 驳回接口
    async rejectApi(api) {
      if (!this.rejectReason.trim()) {
        this.showToastMessage('请输入驳回原因');
        return;
      }

      try {
        const response = await this.$http.post('/api/system/api/reject', {
          apiId: api.apiid,
          reason: this.rejectReason
        });

        if (response.data.code === 200) {
          this.showToastMessage('驳回成功');
          this.showDialog = false;
          this.fetchApiList(); // 刷新列表
        } else {
          throw new Error(response.data.message || '操作失败');
        }
      } catch (error) {
        console.error('驳回失败:', error);
        this.showToastMessage(error.message || '驳回失败');
      }
    },

    // 新增检索方法
    handleSearch() {
      // 构建搜索参数
      const params = {
        ...this.searchParams,
        startTime: this.searchParams.dateRange?.[0],
        endTime: this.searchParams.dateRange?.[1]
      };
      
      // 打印搜索参数到控制台
      console.log('搜索参数:', params);
      
      // 调用获取数据的方法
      this.fetchApiList();
    },

    // 重置搜索条件
    resetSearch() {
      this.searchParams = {
        apiName: '',
        apiId: '',
        creator: '',
        status: '',
        dateRange: null,
        currentPage: 1,
        pageSize: 10
      };
      
      // 重置后自动搜索
      this.handleSearch();
    },

    // 修改分页处理方法
    handleCurrentChange(val) {
      this.searchParams.currentPage = val;
      this.handleSearch();
    },

    handleSizeChange(val) {
      this.searchParams.pageSize = val;
      this.searchParams.currentPage = 1;
      this.handleSearch();
    },

    // 更新统计数据
    updateStats() {
      this.totalApis = this.apiList.filter(api => api.status === '-2').length;
      this.approvedApis = this.apiList.filter(api => api.status === '5').length;
      this.rejectedApis = this.apiList.filter(api => api.status === '-3').length;
    },

    // 添加显示提示消息的方法
    showToastMessage(message) {
      // 清除之前的定时器
      if (this.toastTimer) {
        clearTimeout(this.toastTimer);
      }
      
      // 显示新消息
      this.toastMessage = message;
      this.showToast = true;
      
      // 3秒后自动隐藏
      this.toastTimer = setTimeout(() => {
        this.showToast = false;
      }, 3000);
    },

    // 获取状态类名
    getStatusClass(status) {
      return {
        '-2': 'status-pending',
        '-3': 'status-rejected',
        '5': 'status-approved'
      }[status] || '';
    },

    // 获取状态图标
    getStatusIcon(status) {
      return {
        '-2': 'fas fa-clock',
        '-3': 'fas fa-times-circle',
        '5': 'fas fa-check-circle'
      }[status] || 'fas fa-question-circle';
    },

    // 获取状态文本
    getStatusText(status) {
      return {
        '-2': '待审核',
        '-3': '已驳回',
        '5': '已通过'
      }[status] || '未知状态';
    },

    // 截断文本
    truncateText(text, length) {
      if (!text) return '';
      return text.length > length ? text.slice(0, length) + '...' : text;
    },

    // 处理审核通过
    async handleApprove(row) {
      try {
        await this.$confirm('确认通过该API的审核申请吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        });
        const response = await axios.post('/api/system/api/approve/' + row.apiid);
      
       if (response.data.code === 200) {
          this.$message.success('审核通过成功');
          // 更新状态为已通过(5)
          row.status = 5;
          this.fetchApiList();
        } else {
          this.$message.error(response.data.msg || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作失败'+error);
        }
      }
    },

    // 打开驳回对话框
    handleReject(row) {
      this.currentApi = row;
      this.dialogType = 'reject';
      this.rejectReason = '';
      this.dialogVisible = true;
    },

    // 提交驳回
    async submitReject() {
      try {
        if (!this.rejectReason.trim()) {
          this.$message.warning('请输入驳回原因');
          return;
        }

        const res = await axios.post(`/api/system/api/reject/${this.currentApi.apiid}`, {
          reject: this.rejectReason
        });

        if (res.data.code === 200) {
          this.$message.success('已驳回');
          this.dialogVisible = false;
          this.fetchApiList();
        } else {
          this.$message.error(res.data.msg || '操作失败');
        }
      } catch (error) {
        this.$message.error('操作失败');
      }
    },

    // 关闭对话框
    handleDialogClose() {
      this.dialogVisible = false;
      this.dialogType = '';
      this.currentApi = null;
      this.rejectReason = '';
    },

    // 添加缺失的表格行类名方法
    tableRowClassName({ row, rowIndex }) {
      // 可以根据需要返回不同的类名
      return '';
    }
  },

  created() {
    // 初始加载时执行搜索
    this.handleSearch();
  },

  // 组件销毁时清除定时器
  beforeDestroy() {
    if (this.toastTimer) {
      clearTimeout(this.toastTimer);
    }
  }
};
</script>

<style scoped>
.api-review {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
}

.review-card {
  background-color: var(--card-bg);
  border-color: var(--border-color);
}

/* 基础样式 */
.api-review {
  min-height: 100vh;
  padding: 2rem;
  background: #f0f2f5;
  position: relative;
}

/* 动态背景 */
.animated-bg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.light-beam {
  position: absolute;
  width: 200%;
  height: 200%;
  top: -50%;
  left: -50%;
  background: linear-gradient(
    45deg,
    rgba(66, 133, 244, 0.1) 0%,
    rgba(66, 133, 244, 0.05) 100%
  );
  animation: rotate 20s linear infinite;
}

.particles {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: radial-gradient(circle at center, #4285f4 1px, transparent 1px);
  background-size: 50px 50px;
  animation: float 20s linear infinite;
}

.cyber-grid {
  position: absolute;
  width: 200%;
  height: 200%;
  top: -50%;
  left: -50%;
  background-image: 
    linear-gradient(rgba(66, 133, 244, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(66, 133, 244, 0.05) 1px, transparent 1px);
  background-size: 30px 30px;
  animation: grid-move 20s linear infinite;
}

/* 统计卡片 */
.stats-header {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: white;
  padding: 2rem;
  border-radius: 16px;
  display: flex;
  align-items: center;
  gap: 1.5rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card i {
  font-size: 2.5rem;
  color: #1a237e;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: #1a237e;
}

.stat-label {
  color: #666;
  margin-top: 0.5rem;
}

/* 筛选器 */
.filter-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.filter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.filter-item label {
  font-weight: 500;
  color: #666;
}

.date-range {
  grid-column: span 2;
}

.filter-actions {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

/* 表格样式 */
.table-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* API名称单元格 */
.api-name-cell {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.api-icon {
  width: 40px;
  height: 40px;
  background: #f0f4ff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1a237e;
}

.api-info {
  display: flex;
  flex-direction: column;
}

.api-title {
  font-weight: 500;
}

.api-id {
  font-size: 0.9rem;
  color: #666;
}

/* 状态徽章 */
.status-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-size: 0.9rem;
}

.status-approved {
  background: rgba(76, 175, 80, 0.1);
  color: #4caf50;
}

.status-pending {
  background: rgba(255, 152, 0, 0.1);
  color: #ff9800;
}

.status-rejected {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

/* 类型徽章 */
.type-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: #f0f4ff;
  color: #1a237e;
  border-radius: 20px;
  font-size: 0.9rem;
}

/* 创建者单元格 */
.creator-cell {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.creator-name {
  font-weight: 500;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 0.5rem;
}

/* 分页器 */
.pagination-section {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.review-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.dialog-content {
  padding: 1rem 0;
}

.approve-confirm {
  text-align: center;
  padding: 2rem;
}

.approve-confirm i {
  font-size: 4rem;
  color: #4caf50;
  margin-bottom: 1rem;
}

/* Toast提示 */
.toast {
  position: fixed;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%) translateY(100px);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 1rem 2rem;
  border-radius: 30px;
  transition: all 0.3s ease;
}

.toast.show {
  transform: translateX(-50%) translateY(0);
}

/* 动画效果 */
@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-30px); }
}

@keyframes grid-move {
  from { transform: translateY(0); }
  to { transform: translateY(30px); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .api-review {
    padding: 1rem;
  }
  
  .stats-header {
    grid-template-columns: 1fr;
  }
  
  .filter-grid {
    grid-template-columns: 1fr;
  }
  
  .date-range {
    grid-column: span 1;
  }
  
  .filter-actions {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .api-review {
    background: #121212;
  }
  
  .stat-card,
  .filter-section,
  .table-section {
    background: rgba(30, 30, 30, 0.95);
    color: #fff;
  }
  
  .stat-card i,
  .stat-value {
    color: #64b5f6;
  }
  
  .filter-item label {
    color: #aaa;
  }
  
  .api-icon {
    background: #1a365d;
    color: #64b5f6;
  }
  
  .type-badge {
    background: #1a365d;
    color: #64b5f6;
  }
  
  .api-id {
    color: #888;
  }
}

.el-dialog__body {
  padding: 20px 30px;
}

.reject-form {
  margin-top: 20px;
}

.reject-form .el-textarea__inner {
  resize: none;
}
</style>
  